package com.qf.mrmd.exception;

import com.alibaba.fastjson.JSONObject;
import com.qf.mrmd.result.ResponseCode;
import com.qf.mrmd.result.ResponseData;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@Component
public class GlobalException implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        /**
         * 开始对异常进行判断    Exception e
         * 1.运行时异常
         * 2.SQL异常
         * 3.系统异常
         *
         * 将异常信息返回给前端
         */
        JSONObject jsonObject = new JSONObject();
        if (ex instanceof  BusinessException){
            BusinessException businessException = (BusinessException) ex;
            //将值返回给前端 ecode info
            jsonObject.put("ecode",businessException.getEcode());
            jsonObject.put("info",businessException.getInfo());
        }else if (ex instanceof SQLException){
            jsonObject.put("ecode", ResponseCode.SQL_EXCEPTION.getEcode());
            jsonObject.put("info",ResponseCode.SQL_EXCEPTION.getInfo());
        }else {
            jsonObject.put("ecode", ResponseCode.SYSTEM_EXCEPTION.getEcode());
            jsonObject.put("info",ResponseCode.SYSTEM_EXCEPTION.getInfo());
        }

        try {
            response.setContentType("text/html;charset=utf-8"); //设置相应编码
            response.getWriter().write(jsonObject.toString());
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
